import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import axios from 'axios';
import { getAdvertise, createAdvertise, updateAdvertise, deleteAdvertise, getIdAdvertise, advertiseStatusChange, createFile, findFileById, deleteFileById } from './advertise.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let status = request.query.status
  let pageNo = request.query.pageNo
  let type = request.query.type
  let data = await getAdvertise(parseInt(`${status}`, 10), 10, parseInt(`${pageNo}`, 10), parseInt(`${type}`, 10));

  let weather = null;
  // 实时天气
  const key = '0dd664cac9bbeeed567e1d842573120f';
  const city = '阿图什';
  const str = encodeURI(city)
  const url = 'https://restapi.amap.com/v3/weather/weatherInfo?city=' + str + '&key=' + key;
  await axios.get(url).then(async res => {
    weather = res.data.lives[0]
  }).catch(error => {
    console.log('error: ', error)
  })

  for (let item of data.data as any) {
    item.weather = weather
  }
  
  response.send(data);
}

/**
 * 获取内容(按 ID 查找)
 */
export const advertiseDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 调取内容
  try {
    const data = await getIdAdvertise(parseInt(postId, 10));

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let advertiseModel = request.body;

  // advertiseModel.status = 0;
  // let user = request.user;
  // if (user.type != 1) {
  //   advertiseModel.user_id = user.id
  // }

  // 创建内容
  if (advertiseModel.id && advertiseModel.id > 0) {
    let image_id = advertiseModel.image_id
    let img = await findFileById(image_id, 0, 0);
    
    if (!img || img.length === 0) {
      let imgs = await findFileById(0, advertiseModel.id, 20);
      if (imgs && imgs.length > 0) {
        advertiseModel.image_id = imgs[imgs.length - 1].id
      }
    }
    const data = await updateAdvertise(advertiseModel, parseInt(advertiseModel.id, 10));
    response.send(data);
  } else {
    const data = await createAdvertise(advertiseModel);
    response.send(data);
  }
}

/**
 * 更新内容
 */
export const update = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { postId } = request.params;

  // 获取内容
  const post = _.pick(request.body, [
    'status',
    'name_zh',
    'name_ug',
    'price',
    'content_zh',
    'content_ug'
  ]);


  // 更新内容
  try {
    const data = await updateAdvertise(post, parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.body;

  // 删除内容
  try {
    const data = await deleteAdvertise(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 状态
 */
export const status = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 获取内容 ID
  const postId = request.body.id;


  // 获取内容
  const post = _.pick(request.body, ['status']);

  // 执行
  try {
    const data = await advertiseStatusChange(parseInt(postId, 10), post);
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 上传文件
 */
export const uploads = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取类型
  let { target_type, target_id } = request.body;
  if (target_id === undefined) {
    target_type = request.query.target_type;
    target_id = request.query.target_id;
  }

  // 文件信息
  const fileInfo = _.pick(request.file, [
    'id',
    'target_id',
    'target_type',
    'url',
    'originalname',
    'mimetype',
    'filename',
    'size'
  ])

  fileInfo['url'] = "/advertise/";
  fileInfo['target_type'] = parseInt(`${target_type}`, 10);
  fileInfo['target_id'] = parseInt(`${target_id}`, 10);

  try {
    // 保存文件信息
    const data = await createFile({
      ...fileInfo,
      ...request.fileMataData,
      //target_type: parseInt(`${target_type}`, 10), // target_type: `${target_type}` // target_type: target_type as string  转换字符串两种写法
    })

    let post = {
      id: parseInt(`${target_id}`, 10),
      image_id: (data as any).insertId,
    }

    const advertiseData = await updateAdvertise(post as any, parseInt(`${target_id}`, 10));

    // 做出响应
    response.status(200).send(advertiseData)
  } catch (error) {
    next(error);
  }
}

/**
 * 文件服务
 */
export const serve = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 从地址参数里得到文件 ID
  const { fileId } = request.params;

  try {
    // 查找文件信息
    const file = await findFileById(parseInt(fileId, 10), 0, 0);

    // 做出响应
    response.sendFile(file.filename, {
      root: 'uploads/advertise',
      headers: {
        'Content-Type': file.mimetype
      }
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 获取文件名
 */
export const getFileName = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取文件 ID
  const { fileId } = request.body;
  let file = await findFileById(fileId, 0, 0)
  if (!file || file.length <= 0) {
    response.send({
      status: 2,
      msg: 'not found'
    })
    return;
  }
  let result = await deleteFileById(file[0])

  response.send({
    status: 1,
    msg: 'ok'
  })
}